package com.grantha.bean;

import java.sql.ResultSet;

import org.apache.log4j.Logger;

import com.grantha.util.DB;
import com.grantha.util.Util;

import net.sf.json.JSONObject;

public class Library {

	Logger log = Logger.getLogger(this.getClass());

	public JSONObject addBook(Book b) {

		try {

			log.info("id checking");

			ResultSet rs = DB
					.search("select max(bookno) as booknomax from bookregister");
			if (rs.next()) {
				int maxBookNo = Integer.parseInt(rs.getString("booknomax")) + 1;

				DB.update(
						"insert into bookregister (author, billno,bookno, classno,cost,date,edition,isbn,moreinfo,pages,publisher,source ,subject,title,volume,year) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
						b.getAuthor(), b.getBillno(), maxBookNo + "",
						b.getClassno(), b.getCost(), b.getDate(),
						b.getEdition(), b.getIsbn(), b.getMoreinfo(),
						b.getPages(), b.getPublisher(), b.getSource(),
						b.getSubject(), b.getTitle(), b.getVolume(),
						b.getYear());

				log.info("success");
				return Util.sendJSONObj(true, "Book added successfully");
			}
		} catch (Exception e) {

			log.error("Error");

		}

		return Util.sendJSONObj(false, "Error when adding book");

	}

	public JSONObject addPatron(Patron p) {
		return null;
	}

	public JSONObject updateBook(Book b) {
		return null;
	}

	public JSONObject updatePatron(Patron p) {
		return null;
	}

	public JSONObject issueBook(String b, String p) {
		try {

			DB.update(
					"insert into dailyissueregister (bookno,patno,dateofissue,returned) values (?, ?,curdate(),'false')",
					b, p);
			
			log.info("book issued");
			return Util.sendJSONObj(true, "Issued Successfully");
			
		} catch (Exception e) {
			log.error("error when issuing");
			return Util.sendJSONObj(false, "Error when issuing book");
		}
	}

	public JSONObject returnBook(int b) {
		return null;
	}

	public JSONObject reserveBook(int b, int p) {
		return null;
	}

	/**
	 * @param are
	 *            still not defined
	 * @return
	 */
	public Book serachBook() {
		return null;
	}

	/**
	 * @param are
	 *            still not defined
	 * @return
	 */
	public Patron serachPatron() {
		return null;
	}

	public JSONObject addUser(User u) throws Exception {

		DB.update(
				"insert into users (username, password, rights) values (?, ?, ?)",
				u.getUserName(), u.getPassword(), u.getRights());

		return null;
	}

	public JSONObject updateUser(User u) {
		return null;
	}
}
